import axios from 'axios'
import storage from 'store'
import { ACCESS_TOKEN, ACCESS_TOKEN_BRAND, BRANDID } from './types'
import qs from 'qs'
import { Dialog , Notify } from 'vant';
import stroe from '../store';
import router from '../router';
import brandApi from '@/api/brand';
import { dataEncryption } from './index';

// 创建 axios 实例
const request = axios.create({
    // API 请求的默认前缀
    baseURL: process.env.VUE_APP_API_BASE_URL,
    timeout: 6000 // 请求超时时间
})

const _getToken = async() => {
    var token = await brandApi.getToken(storage.get(BRANDID))
    var brandToken = await brandApi.getToken(1)
    storage.set(ACCESS_TOKEN,token[ACCESS_TOKEN])
    storage.set(ACCESS_TOKEN_BRAND,brandToken[ACCESS_TOKEN])
}
// 每次请求去掉空值参数
function delNoneParameter(data){
    let obj = new Object()
    Object.keys(data).sort().map(function(key){
        // 判断key值的类型，文件的过滤掉
        if(data[key] !== "" && data[key] != undefined && data[key] != null && data[key] != 'null'){
            obj[key] = data[key]
        }
    })
    return obj
}

let needLoadingRequestCount = 0
let timer = null
function showFullScreenLoading() {
    // console.log(timer,'starttimer')
    if (needLoadingRequestCount === 0 && !timer) {
        timer = setTimeout(()=>{
            stroe.dispatch('setLoading',true)
        },500)
    }
    needLoadingRequestCount++
}

 function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
        needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        if(timer){
            clearTimeout(timer)
            timer = null
            stroe.dispatch('setLoading',false)
        }
    }
}

// 异常拦截处理器
const errorHandler = async (error) => {
    tryHideFullScreenLoading()
    if (error.response) {
        const data = error.response
        // 从 localstorage 获取 token
        const token = storage.get(ACCESS_TOKEN)
        if (error.response.status === 403) {
            Notify({ type: 'danger', message: data.errMessage });
        }
        if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
            await _getToken();
            return instance(error.config);
        }
    }
    return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
    showFullScreenLoading()
    const token = storage.get(ACCESS_TOKEN)
    const brandToken = storage.get(ACCESS_TOKEN_BRAND)
    // 如果 token 存在
    // 让每个请求携带自定义 token 请根据实际情况自行修改
    if(!config.headers.file){
        for ( var key in config.data ){
            if ( (!config.data[key] || config.data[key] === '') && config.data[key] !== 0){
                delete config.data[key]
            }
        }
        if(config.headers.isSign){
            if(config.method == 'post'){
                config.data = delNoneParameter(Object.assign(qs.parse(qs.stringify(config.data)),dataEncryption(qs.parse(qs.stringify(config.data)))))
            }else if(config.method == 'get'){
                // console.log(config.params)
                config.params = config.params || {}
                config.params = delNoneParameter(Object.assign(config.params,dataEncryption(qs.parse(qs.stringify(config.params)))))
            }
        }else{
            if ((token || brandToken) && config.url != '/app/login/client') {
                var tokenObj = new Object()
                if(config.headers.isBrand){
                    tokenObj[ACCESS_TOKEN] = brandToken
                }else{
                    tokenObj[ACCESS_TOKEN] = token
                }
                config.data = Object.assign(config.data,tokenObj)
            }
        }
        config.data = qs.stringify(config.data)
    }else{
        config.data.append(ACCESS_TOKEN,token)
    }
    // console.log(config,'config')
    return config
}, errorHandler)

// response interceptor
request.interceptors.response.use(async(response) => {
    tryHideFullScreenLoading()
    if(response.data.errCode == 'ERROR_TOKEN'){
        // token 过期的操作
        // Dialog.confirm({
        //     title: '登录过期',
        //     message: '您的登录已经过期，请重新登录',
        // })
        // .then(() => {
        //     // on confirm
        //     storage.clearAll()
        //     // window.location.reload()
        //     router.push({name:'login'})
        // })
        // .catch(() => {
        //     // on cancel
        // });
        await _getToken();
        return request(response.config);
    }else if(response.url != '/accountcenter/app/request/ali/top/up'){
        return response.data
    }else{
        return response
    }
}, errorHandler)

export default request